import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    meta: {
      title: "首页",
    },
    component: Home,
  },
  {
    path: "/detail/:id",
    name: "Detail",
    component: () => import("../views/Detail.vue"),
  },
  {
    path: "/category/:id",
    name: "Category",
    meta: {
      title: "分类",
    },
    component: () => import("../views/Category.vue"),
  },
  {
    path: "/car",
    name: "Car",
    meta: {
      title: "购物车",
    },
    component: () => import("../views/Car.vue"),
  },
  {
    path: "/check",
    name: "Check",
    meta: {
      title: "订单",
      requiresAuth: true,
    },
    component: () => import("../views/Check.vue"),
  },
  {
    path: "/search/wd/:wd",
    name: "SearchParams",
    meta: {
      title: "搜索",
    },
    component: () => import("../views/Search.vue"),
  },
  {
    path: "/search/wd",
    name: "Search",
    meta: {
      title: "搜索",
    },
    component: () => import("../views/Search.vue"),
  },
  {
    path: "/login",
    name: "Login",
    meta: {
      title: "登录",
    },
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/register",
    name: "Register",
    meta: {
      title: "注册",
    },
    component: () => import("../views/Register.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 付款页面需要登录
router.beforeEach((to, _from, next) => {
  // 判断该路由是否需要登录权限
  if (to.meta.requiresAuth) {
    // 路由需要验证，判断用户是否已经登录
    if (store.state.user) {
      next();
    } else {
      next({
        path: "/login",
      });
    }
  } else {
    next();
  }
});

// 设置页面的标题
router.afterEach((to) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  }
});

export default router;
